<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>WebSocket</title>
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
</head>

<body>
<div id="main" style="width: 1200px">
    <h1>Welcome</h1>
    <div>
        <button onclick="send()">发送消息</button>
        <button onclick="closeWebSocket()">关闭WebSocket连接</button>
        <button onclick="openWebSocket()">WebSocket连接</button>

    </div>

    <div>
        <span>current-user:</span><input id="current-user"/><span>current-id:</span><span id="current-id"></span>span>
        <button onclick="register()">注册</button>
    </div>

    <div id="users"></div>
    <div>
        <span>send-user-id:</span><input id="send-user"/></br>
        <span>msg:</span><input id="msg"/>
    </div>
    <div id="message"></div>

    <script type="text/javascript">



        var currentUesr = {};


      function  register(){
          //注册
          var url = 'http://localhost:8083/registerAccount';
          var data = {
              "userName": "test-" + document.getElementById('current-user').value,
              "reqNo": "demoData",
              "timeStamp": 0
          }
          $.ajax({
              type: "post",
              url: url,
              async: false,
              // 1 需要使用JSON.stringify 否则格式为 a=2&b=3&now=14...
              // 2 需要强制类型转换，否则格式为 {"a":"2","b":"3"}
              data: JSON.stringify(data),
              contentType: "application/json; charset=utf-8",
              success: function (data) {
                  console.log(data.dataBody);
                  currentUesr.userId = data.dataBody.userId;
                  currentUesr.userName = data.dataBody.userName;
                  document.getElementById('current-id').innerHTML=data.dataBody.userId;
              }, error: function () {
                  alert(data.dataBody);
              }
          });


          // 登录
          var url_login = 'http://localhost:8083/login';
          var data_login = {
              "userId": currentUesr.userId,
              "userName": currentUesr.userName,
              "reqNo": "demoData",
              "timeStamp": 0
          }

          $.ajax({
              type: "post",
              url: url_login,
              // 1 需要使用JSON.stringify 否则格式为 a=2&b=3&now=14...
              // 2 需要强制类型转换，否则格式为 {"a":"2","b":"3"}
              data: JSON.stringify(data_login),
              contentType: "application/json; charset=utf-8",
              success: function (data) {
                  console.log(data.dataBody);

                  // 获取登录用户
                  $.ajax({
                      type: "post",
                      url: 'http://localhost:8083/onlineUser',
                      data: JSON.stringify({}),
                      contentType: "application/json; charset=utf-8",
                      success: function (data) {
                          console.log(data.dataBody);
                          document.getElementById('users').innerHTML += JSON.stringify(data.dataBody);
                      }
                  });

              }
          });
      }

        var websocket = null;

        function openWebSocket() {
            //判断当前浏览器是否支持WebSocket
            if ('WebSocket' in window) {
                //改成你的地址
                websocket = new WebSocket("ws://localhost:11211");
                //连接发生错误的回调方法
                websocket.onerror = function () {
                    setMessageInnerHTML("WebSocket连接发生错误");
                };




                //连接成功建立的回调方法
                websocket.onopen = function () {
                    setMessageInnerHTML("WebSocket连接成功");
                }
                var U01data, Uidata, Usdata
                //接收到消息的回调方法
                websocket.onmessage = function (event) {
                    console.log(event);
                    setMessageInnerHTML(event);
                    setechart()
                }

                //连接关闭的回调方法
                websocket.onclose = function () {
                    setMessageInnerHTML("WebSocket连接关闭");
                }

            } else {
                alert('当前浏览器 Not support websocket')
            }
        }


        //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
        window.onbeforeunload = function () {
            closeWebSocket();
        }

        //将消息显示在网页上
        function setMessageInnerHTML(innerHTML) {
            document.getElementById('message').innerHTML += innerHTML + '<br/>';
        }

        //关闭WebSocket连接
        function closeWebSocket() {
            websocket.close();
        }

        //发送消息
        function send() {
            var message = document.getElementById('msg').value;
            var data = {
                "userId": currentUesr.userId,
                "receiveUserId": document.getElementById('send-user').value,
                "msg": message,
                "reqNo": "demoData",
                "timeStamp": 0
            }
            /* websocket的几个状态。通常在实例化一个websocket对象之后，客户端就会与服务器进行连接。但是连接的状态是不确定的，于是用readyState属性来进行标识。它有四个值，分别对应不同的状态：

              CONNECTING：值为0，表示正在连接；
OPEN：值为1，表示连接成功，可以通信了；
CLOSING：值为2，表示连接正在关闭；
CLOSED：值为3，表示连接已经关闭，或者打开连接失败。*/
            if(websocket.readyState===1){
                websocket.send(data);
                setMessageInnerHTML(message + "&#13;");
            }else{
                alert("ws链接状态"+websocket.readyState);
            }


        }
    </script>
</body>

</html>
